package com.auto.survey.activity.test

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.auto.survey.R
import com.auto.survey.activity.bluetooth.BluetoothManagerUtil
import com.auto.survey.log.AppLogger

class TestAdapter(activity: TestActivity, bluetoothmanager: BluetoothManagerUtil, viewModle: TestViewModle)  : Adapter<TestAdapter.TestViewHodler>() {

    private val mDatas = mutableListOf<Map<String, List<String>>>()
    private val mActivity = activity
    private val mBluetoothmanager = bluetoothmanager
    private val mViewModle = viewModle

    fun setItems(itemdatas:MutableList<Map<String, List<String>>>) {
        mDatas.clear()
        mDatas.addAll(itemdatas)
        notifyDataSetChanged()
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TestViewHodler {
        val itemview = LayoutInflater.from(parent.context).inflate(R.layout.item_test_layout, parent, false)
        return TestViewHodler(itemview)
    }

    override fun getItemCount(): Int {
        return mDatas.size
    }

    override fun onBindViewHolder(holder: TestViewHodler, position: Int) {

        val key = mDatas[position].keys.toList()[0]
        holder.textViewItem.text = key
        holder.textViewItem.setOnClickListener {
            val commList = mutableListOf<String>()
            commList.add(key)
            Log.i("TestActivity", "开始发送命令操作: $key")
            AppLogger.getInstance(mActivity).i("TestActivity", "开始发送命令操作: $key")
            val strCommands = mDatas[position][key]

            val executor = CommandExecutor()
            executor.setResultExecutorCallback {
                it.forEach {
                    val rlt = "获取 $key 命令结果: $it"
                    Log.i("TestActivity", rlt)
                    AppLogger.getInstance(mActivity).i("TestActivity", rlt)
                    commList.add(rlt)
                }

                mViewModle.getBlueToothCommunity(commList)
            }
            val doExecutor = mutableListOf<TestCommandExecutor>()
            strCommands?.forEach {
                doExecutor.add(TestCommandExecutor(mActivity, mBluetoothmanager, it))
            }
            executor.startExecution(doExecutor)
        }
    }



    inner class TestViewHodler(item: View): ViewHolder(item){
        val textViewItem = item.findViewById<TextView>(R.id.tv_test_item)
    }

}